<template>
  <div>
    <a-row class="j-select-row" type="flex" :gutter="8">
      <a-col class="left" :class="{ full: !showButton }">
        <!-- 显示加载效果 -->
        <a-input v-if="loadingState" readOnly placeholder="加载中…">
          <template #prefix>
            <LoadingOutlined />
          </template>
        </a-input>
        <a-select v-else ref="select" v-model:value="selectValues.value" :placeholder="placeholder" :mode="multiple" :open="false" :disabled="disabled" :options="selectOptions" :maxTagCount="maxTagCount" @change="handleChange" style="width: 100%" @click="!disabled && openModal(false)"></a-select>
      </a-col>
      <a-col v-if="showButton" class="right">
        <a-button v-if="buttonIcon" :preIcon="buttonIcon" type="primary" @click="handlerOpenModal" :disabled="disabled">选择</a-button>
        <a-button v-else type="primary" @click="handlerOpenModal" :disabled="disabled">选择</a-button>
      </a-col>
    </a-row>
    <a-form-item-rest>
      <SelectModal @register="regModal" v-bind="getBindValue" @getSelectResult="setValue"></SelectModal>
    </a-form-item-rest>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, inject, unref, watch } from 'vue';
import { useAttrs } from '@pkg/use';
import { LoadingOutlined } from '@ant-design/icons-vue';

import { useModal } from '@/components/modal';
import { createAsyncComponent } from '@/internal';
import { request } from '@pkg/request/src';
export default defineComponent({
  name: 'SelectComp',
  components: { LoadingOutlined, SelectModal: createAsyncComponent(() => import('../modal/SelectModal.vue'), { loading: true }) },
  inheritAttrs: false,
  props: {
    showButton: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    // 是否支持多选，默认 true
    multiple: {
      type: [String, Boolean],
      default: 'multiple',
    },
    // 是否正在加载
    loading: {
      type: Boolean,
      default: false,
    },
    // 最多显示多少个 tag
    maxTagCount: {
      type: Number,
    },
    // buttonIcon
    buttonIcon: {
      type: String,
      default: '',
    },
    //查询表单配置
    formConfig: {
      type: Object,
    },
    //表格列配置
    columns: {
      type: Object,
      default: [],
    },
  },
  emits: ['handleOpen', 'change','selectOk'],
  setup(props, { emit }) {
    //注册model
    const [regModal, { openModal }] = useModal();
    //下拉框选项值
    const selectOptions = ref([]);
    // 是否正在加载回显数据
    const loadingState = ref<boolean>(false);
    //接收选择的值
    const selectValues = inject('selectValues') || ref(<any>{});
    const attrs = useAttrs();
    const getBindValue: any = Object.assign({}, unref(props), unref(attrs));
    console.info("getBindValue",getBindValue);
    //接口地址
    const tableApi = getBindValue.api;
    /**
     * 下拉框值改变事件
     */
    function handleChange(value) {
      console.info('handleChange', value);
      selectValues.value = value;
      selectValues.change = true;
      emit('change', value,selectOptions);
    }

    function handlerOpenModal() {
      openModal(true, {
        props,
      });
    }
    /**
     * 设置下拉框的值
     */
    function setValue(options, values,selectRows) {
      selectOptions.value = options;
      selectValues.value = values;
      emit("selectOk",selectOptions,selectValues,selectRows)
    }

    /**
     * 监听selectValues给selectOptions赋值
     */
    watch(
      selectValues,
      async () => {
        if (selectValues['change'] == false) {
          let selectIds = selectValues.value.join(',');
          let options = <any>[];
          if (selectIds) {
            loadingState.value = true;
            let { records } = await getList({
              selectIds: selectIds,
            });
            loadingState.value = false;
            records.forEach((item) => {
              options.push({ label: item[getBindValue.labelKey], value: item[getBindValue.rowKey] });
            });
          }
          selectOptions.value = options;
        }
      },
      { immediate: true },
    );

    /**
     *  回显数据查询
     * @param params
     */
    async function getList(params) {
      return request.get({ url: tableApi, params }, { successMessageMode: 'none' });
    }

    return {
      attrs,
      selectValues,
      selectOptions,
      getList,
      regModal,
      getBindValue,
      setValue,
      loadingState,
      handlerOpenModal,
      handleChange,
      openModal,
    };
  },
});
</script>
<style lang="less" scoped>
.j-select-row {
  @width: 82px;

  .left {
    width: calc(100% - @width - 8px);
  }

  .right {
    width: @width;
  }

  .full {
    width: 100%;
  }

  ::v-deep(.ant-select-search__field) {
    display: none !important;
  }
}
</style>
